package com.xinya.wanandroidclient.base;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import com.scwang.smart.refresh.layout.SmartRefreshLayout;

/**
 * @ClassName: BaseFragment$
 * @Description: java类作用描述
 * @Author: xinya
 * @CreateDate: 2021/2/23$ 17:02$
 * @UpdateRemark: 更新内容
 * @Version: 1.0
 */
public abstract class BaseFragment extends Fragment {
    private Context mContext;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.mContext = context;
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        ViewDataBinding binding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false);
        binding.setLifecycleOwner(getViewLifecycleOwner());
        initDataBinding(binding);
        
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(savedInstanceState);

        observer();
        onClick();
    }


    protected abstract int getLayoutId();

    protected abstract void init(Bundle savedInstanceState);

    public void initDataBinding(ViewDataBinding binding) {

    }

    public void observer() {

    }

    public void onClick() {

    }


    private ViewModelProvider activityProvider = null;

    public <T extends ViewModel> T getActivityViewModel(Class<T> clazz) {
        if (activityProvider == null) {
            activityProvider = new ViewModelProvider((AppCompatActivity) mContext);
        }
        return activityProvider.get(clazz);
    }

    private ViewModelProvider fragmentProvider = null;

    public <T extends ViewModel> T getFragmentVieModel(Class<T> clazz) {
        if (fragmentProvider == null) {
            fragmentProvider = new ViewModelProvider(this);
        }
        return fragmentProvider.get(clazz);
    }

    public void smartRefreshState(SmartRefreshLayout smartRefreshLayout, boolean isSuccess) {
        if (isSuccess) {
            smartRefreshLayout.finishRefresh(0);
            smartRefreshLayout.finishLoadMore(0);
            return;
        }

        smartRefreshLayout.finishRefresh(0, false, null);
        smartRefreshLayout.finishLoadMore(0, false, false);
    }

}
